package sunyu.controller.shiro.exception.resolver;


import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import sunyu.kit.common.LogKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * shiro异常处理
 * <p>
 * 需要在spring上下文配置
 * <p>
 * <bean id="shiroHandlerExceptionResolver" class="sunyu.controller.shiro.exception.resolver.ShiroHandlerExceptionResolver" />
 *
 * @author 孙宇
 */
public class ShiroHandlerExceptionResolver implements HandlerExceptionResolver {
    private static final Logger logger = LogKit.getLogger();

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {

        String stackTrace = ExceptionUtils.getStackTrace(ex);

        if (ex instanceof org.apache.shiro.authz.AuthorizationException) {
            logger.info("没有权限!");
        } else if (ex instanceof org.apache.shiro.authz.UnauthenticatedException) {
            logger.info("未登录!");
        } else {
            logger.error(stackTrace);
        }

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("exception", stackTrace.replaceAll("\r\n", "<br/>"));

        String view = "/shiro/error/defaultError";

        if (ex instanceof org.apache.shiro.authz.UnauthenticatedException) {//未登录
            view = "/shiro/login";
        } else if (ex instanceof org.apache.shiro.authz.AuthorizationException) {//没有权限
            view = "/shiro/error/unauthorized";
        }

        return new ModelAndView(view, model);
    }
}
